﻿@using Model;
@{
    Layout = "~/Shared/_SiteLayout.cshtml";
    Page.Title = "Register an Account";

    var email = "";
    var password = "";
    var confirmPassword = "";

    // Validation
    var isValid = true;
    var emailErrorMessage = "";
    var passwordErrorMessage = "";
    var confirmPasswordMessage = "";
    var accountCreationErrorMessage = "";
    var captchaMessage = "";
    Profile NewProfile = new Profile();

    // If this is a POST request, validate and process data
    if (IsPost)
    {
        if (!Request.Form["ReadingClass"].IsEmpty() && Request.Form["ReadingClass"].IsInt())
        {

            NewProfile.ReadingClass = Request.Form["ReadingClass"].AsInt();
            if (NewProfile.ReadingClass < Question.MinClass || NewProfile.ReadingClass > Question.MaxClass)
            {
                NewProfile.ReadingClassError = "Class should be " + Question.MinClass + " to " + Question.MaxClass + " !";
                isValid = false;
            }
        }
        else
        {
            NewProfile.ReadingClassError = "Enter valid Class!";
            isValid = false;
        }

        email = Request.Form["email"];
        password = Request.Form["password"];
        confirmPassword = Request.Form["confirmPassword"];

        //Validate the user's captcha answer
        //if (!ReCaptcha.Validate(WebSite.ReCaptcha_PRIVATE_KEY))
        //{
        //    captchaMessage = "Captcha response was not correct";
        //    isValid = false;
        //}

        // Validate the user's email address
        if (email.IsEmpty())
        {
            emailErrorMessage = "You must specify an email address.";
            isValid = false;
        }

        // Validate the user's password and password confirmation
        if (password.IsEmpty())
        {
            passwordErrorMessage = "The password cannot be blank.";
            isValid = false;
        }

        if (password != confirmPassword)
        {
            confirmPasswordMessage = "The new password and confirmation password do not match.";
            isValid = false;
        }

        // If all information is valid, create a new account
        if (isValid)
        {
            // Insert a new user into the database
            var db = DBObject.Open();

            // Check if user already exists
            var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", email);
            if (user == null)
            {
                // Insert email into the profile table
                db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);
                NewProfile.UserId = SiteSecurity.GetUserId(email);

                // db.Execute("INSERT INTO Profile (UserId,ReadingClass) VALUES (@0,@1)", NewProfile.UserId,NewProfile.ReadingClass);
                
                SiteHelper.AddProfile(NewProfile);

                Roles.AddUserToRole(email, UsersRoles.User);
                
                // Create and associate a new entry in the membership database.
                // If successful, continue processing the request
                try
                {
                    bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
                    var token = SiteSecurity.CreateAccount(email, password, requireEmailConfirmation);
                    if (requireEmailConfirmation)
                    {
                        var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                        var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));

                        WebMail.Send(
                            to: email,
                            subject: "Please confirm your account",
                            body: "Your confirmation code is: " + token + ". Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a> to activate your account."
                        );
                    }

                    if (requireEmailConfirmation)
                    {
                        // Thank the user for registering and let them know an email is on its way
                        Response.Redirect("~/Account/Thanks");
                    }
                    else
                    {
                        // Navigate back to the homepage and exit
                        SiteSecurity.Login(email, password);
                        Response.Redirect("~/");
                    }
                }
                catch (System.Web.Security.MembershipCreateUserException e)
                {
                    isValid = false;
                    accountCreationErrorMessage = e.ToString();
                }
            }
            else
            {
                // User already exists
                isValid = false;
                accountCreationErrorMessage = "Email address is already in use.";
            }
        }
    }

}
<p>
    Use the form below to create a new account.
</p>
@* If at least one validation error exists, notify the user *@
@if (!isValid)
{
    <p class="message error">
        @if (accountCreationErrorMessage.IsEmpty())
        {
            @:Please correct the errors and try again.
    }
        else
        {
            @accountCreationErrorMessage
        }
    </p>
}
<form method="post" action="">
<fieldset>
    <legend>Sign-up Form</legend>
    <ol>
        <li class="reading-class">
            <label for="class">
                Class:</label>
            <input type="text" id="ReadingClass" name="ReadingClass" title="Class" value="@NewProfile.ReadingClass" @if (!NewProfile.ReadingClassError.IsEmpty())
                                                                                                                    {<text>class="error-field"</text>} />
            @* Write any email validation errors to the page *@
            @if (!NewProfile.ReadingClassError.IsEmpty())
            {
                <label for="email" class="validation-error">@NewProfile.ReadingClassError</label>
            }
        </li>
        <li class="email">
            <label for="email">
                Email or Username :</label>
            <input type="text" id="email" name="email" title="Email address" value="@email" @if (!emailErrorMessage.IsEmpty())
                                                                                            {<text>class="error-field"</text>} />
            @* Write any email validation errors to the page *@
            @if (!emailErrorMessage.IsEmpty())
            {
                <label for="email" class="validation-error">@emailErrorMessage</label>
            }
        </li>
        <li class="password">
            <label for="password">
                Password:</label>
            <input type="password" id="password" name="password" title="Password" @if (!passwordErrorMessage.IsEmpty())
                                                                                  {<text>class="error-field"</text>} />
            @* Write any password validation errors to the page *@
            @if (!passwordErrorMessage.IsEmpty())
            {
                <label for="password" class="validation-error">@passwordErrorMessage</label>
            }
        </li>
        <li class="confirm-password">
            <label for="confirmPassword">
                Confirm Password:</label>
            <input type="password" id="confirmPassword" name="confirmPassword" title="Confirm password" @if (!confirmPasswordMessage.IsEmpty())
                                                                                                        {<text>class="error-field"</text>} />
            @* Write any password validation errors to the page *@
            @if (!confirmPasswordMessage.IsEmpty())
            {
                <label for="confirmPassword" class="validation-error">@confirmPasswordMessage</label>
            }
        </li>
        @* <li class="recaptcha">@ReCaptcha.GetHtml(WebSite.ReCaptcha_PRIVATE_KEY, theme: "white")
            @if (!captchaMessage.IsEmpty())
            {
                <label class="validation-error">@captchaMessage</label>
            }
        </li>*@ @*6LdXDcsSAAAAAOC3cPs-R7GY1wld7rTmL9Hjs4HU*@
    </ol>
    <p class="form-actions">
        <input class="button medium green" type="submit" value="Register" title="Register" />
    </p>
</fieldset>
</form>
